package com.sf.pda;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.litepal.crud.DataSupport;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.sf.config.AppConfig;
import com.sf.config.PdaApp;
import com.sf.config.VolleyQueue;
import com.sf.entity.Company;
import com.sf.entity.Login;
import com.sf.net.JsonUtil;
import com.sf.utils.UtilsLog;

public class LoginActivity extends BaseActivity implements OnClickListener {
	private EditText et_num, et_psd;
	private Button btn_regis, btn_login;
	private Login lg;

	// 获取当前时间
	private String currentTime;
	private List<Company> list = new ArrayList<Company>();
	private String[] str;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.login);
		initView();
		registerListener();
		UtilsLog.e("型号", PdaApp.GetDeviceName());
		UtilsLog.e("是否是idata设备", PdaApp.checkiDataDevice(LoginActivity.this)+"");
	}

	public void initView() {
		lg = new Login();
		et_num = (EditText) findViewById(R.id.et_num);
		et_psd = (EditText) findViewById(R.id.et_psd);
		btn_login = (Button) findViewById(R.id.btn_login);
		btn_regis = (Button) findViewById(R.id.btn_regis);

	}

	public void registerListener() {
		btn_login.setOnClickListener(this);
		btn_regis.setOnClickListener(this);

		et_num.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {
				String numReg = "[0-9]{1,11}";
				if (!TextUtils.isEmpty(source.toString())
						&& !source.toString().matches(numReg)) {
					Toast.makeText(LoginActivity.this, "请输入数字",
							Toast.LENGTH_SHORT).show();
					return "";
				} else {
					return source;
				}

			}
		}, new InputFilter.LengthFilter(11) });
	}

	public boolean checkNum(String str) {
		Pattern pattern = Pattern
				.compile("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
		Matcher m = pattern.matcher(str);
		return m.matches();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login:
			if (TextUtils.isEmpty(et_num.getText().toString().trim())) {
				Toast.makeText(LoginActivity.this, "账号不能为空！",
						Toast.LENGTH_SHORT).show();
				return;
			}
			if (TextUtils.isEmpty(et_psd.getText().toString().trim())) {
				Toast.makeText(LoginActivity.this, "请输入密码！", Toast.LENGTH_SHORT)
						.show();
				return;
			}
			if (!checkNum(et_num.getText().toString().trim())) {
				Toast.makeText(LoginActivity.this, "请输入正确的11位手机号码！",
						Toast.LENGTH_SHORT).show();
				return;
			}

			lg.setMobile(et_num.getText().toString().trim());
			lg.setPassWord(et_psd.getText().toString().trim());
			lg.setIMEI(PdaApp.GetImeiNum(LoginActivity.this));
			// 先查询数据库
			// requestInternet();
			if (verifyUser(lg)) {
				Toast.makeText(LoginActivity.this, "数据库中存在此数据",
						Toast.LENGTH_SHORT).show();
				// 进行跳转
				requestMdInfo();
			} else {
				requestData();
			}
			break;
		case R.id.btn_regis:
			setIntent();
			break;
		}
	}

	public boolean verifyUser(Login lg) {
		List<Login> list = DataSupport.select("mobile", "password").find(
				Login.class);
		for (Login login : list) {
			if (login.getMobile().equals(lg.getMobile())
					&& login.getPassWord().equals(lg.getPassWord())) {
				return true;
			}
		}
		return false;
	}

	// 需要保证参数的顺序
	public String getURL() {
		StringBuffer sBuffer = new StringBuffer();
		sBuffer.append(AppConfig.Login).append("uname=")
				.append(et_num.getText().toString().trim()).append("&pwd=")
				.append(et_psd.getText().toString().trim()).append("&imei=")
				.append(PdaApp.GetImeiNum(LoginActivity.this));
		return sBuffer.toString();
	}

	// 获取门店的url
	public String getMdURL() {
		StringBuffer sb = new StringBuffer();
		sb.append(AppConfig.GetStore).append("time=").append(currentTime);
		return sb.toString();
	}

	// 请求接口
	public void requestData() {

		// if (PdaApp.GetNetworkState(LoginActivity.this)) {
		VolleyQueue.getInstance(LoginActivity.this).add(
				new StringRequest(Method.GET, getURL(), new Listener<String>() {

					@Override
					public void onResponse(String response) {
						UtilsLog.e("====", response);
						Login login = JsonUtil.getData(response);

						if (login != null) {
							lg.setUseId(login.getUseId());
							lg.setStoreid(login.getStoreid());
						}
						// 往数据库中添加数据
						// lg.save();
						UtilsLog.e("flag", lg.toString() + "" + lg.save());
						// 此处进行跳转
						requestMdInfo();

					}
				}, new ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {

					}
				}));
		// }else{
		// Toast.makeText(LoginActivity.this, "请检测您的网络",
		// Toast.LENGTH_SHORT).show();
		// }

	}

	public void setIntent() {
		Intent intent = new Intent(LoginActivity.this,
				PointManagerActivity.class);
		startActivity(intent);
		overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
	}

	@SuppressLint("SimpleDateFormat")
	public void requestMdInfo() {

		Company com = DataSupport.findLast(Company.class);
		if (com != null) {
			currentTime = com.getScoreStartDate();
			str = currentTime.split(" ");
			currentTime = str[0] + "%20" + str[1];
		} else {
			SimpleDateFormat format = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			currentTime = format.format(new java.util.Date());
			str = currentTime.split(" ");
			currentTime = str[0] + "%20" + str[1];
		}

		//if (PdaApp.GetNetworkState(LoginActivity.this)) {
			VolleyQueue.getInstance(LoginActivity.this).add(
					new StringRequest(Method.GET, getMdURL(),
							new Listener<String>() {

								@Override
								public void onResponse(String response) {
									UtilsLog.e("====", response);

									list = JsonUtil.getComList(response);
									// UtilsLog.e("list", list.toString());
									if (list != null) {
										DataSupport.saveAll(list);
									}
									setIntent();
								}
							}, new ErrorListener() {

								@Override
								public void onErrorResponse(VolleyError error) {

								}
							}));
//		} else {
//			setIntent();
//		}
	}
}
